package main.com.controller;

import main.com.dao.UserDao;
import main.com.entry.User;
import main.com.utils.CheckUtil;
import main.com.utils.DateUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author lk
 * @date 2020/6/23 11:28
 * @description: 用户注册
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String password1 = request.getParameter("password1");
        String email = request.getParameter("email");
        String workplace = request.getParameter("workplace");
        UserDao userDao = new UserDao();
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setWorkplace(workplace);
        String msg = null;


        if (!"ok".equals(msg = CheckUtil.checkUserName(username))) {//用户名有误
            user.setUsername(null);
            request.setAttribute("flag", "注册失败");
            request.setAttribute("msg", msg);
            request.setAttribute("user", user);
            request.getRequestDispatcher("wel-reg.jsp").forward(request, response);
        } else if (!"ok".equals(msg = CheckUtil.checkPassWord(password,password1))) {//密码有误
            user.setPassword(null);
            request.setAttribute("flag", "注册失败");
            request.setAttribute("msg", msg);
            request.setAttribute("user", user);
            request.getRequestDispatcher("wel-reg.jsp").forward(request, response);
        } else if (!"ok".equals(msg = CheckUtil.checkEmail(email))) {//邮箱有误
            user.setEmail(null);
            request.setAttribute("flag", "注册失败");
            request.setAttribute("msg", msg);
            request.setAttribute("user", user);
            request.getRequestDispatcher("wel-reg.jsp").forward(request, response);
        } else if (!"ok".equals(msg = CheckUtil.checkWorkPlace(workplace))) {//工作单位有误
            user.setWorkplace(null);
            request.setAttribute("flag", "注册失败");
            request.setAttribute("msg", msg);
            request.setAttribute("user", user);
            request.getRequestDispatcher("wel-reg.jsp").forward(request, response);
        } else {//正常注册
            user.setAddtime(DateUtil.getNowDate());
            userDao.saveUser(user);
            request.setAttribute("flag", "注册成功");
            request.getRequestDispatcher("wel-reg.jsp").forward(request, response);
        }
    }

}
